<?php

namespace Frieza\Modules\PushExcel\Controllers;

use Doraemon\pockets\constInterface\LinkConf;
use Encore\Admin\Grid;
use Biz\tools\helper\Common;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Tab;
use App\Pockets\GridDataModel;
use Doraemon\tools\LinkFormat;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Facades\Admin;
use Biz\model\push\PushLogModel;
use Encore\Admin\Layout\Content;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;

/**
 * @deprecated  没人用下线了
 * Description: wwwroot
 * Created by PhpStorm.
 * User: 玉坤
 * Date: 2021/5/24
 * Time: 18:17
 */
class IndexController extends Controller
{
    public const  PAGE_SIZE = 20;

    /**
     * 获取列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content): Content
    {
        Admin::script($this->operateScript());
        $params = $request->all();
        $page_size = $params['per_page'] ?? self::PAGE_SIZE;
        $page = $params['page'] ?? 1;
        $push_id = $params['push_id'] ?? '';
        $push_name = $params['push_name'] ?? '';
        $count = PushLogModel::count();
        $where['ORDER'] = [
            'creat_time' => 'DESC',
        ];
        $where['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size,
        ];
        if ($push_id) {
            $where['push_id'] = $push_id;
        }
        if ($push_name) {
            $where['push_name[~]'] = $push_name;
        }
        $list = PushLogModel::select('*', $where);
        foreach ($list as &$item) {
            if ((int)$item['push_type'] == PushLogModel::PUSH_TYPE_SPECIAL) {
                $title = json_decode($item['title'], true) ?: [];
                $alert = json_decode($item['alert'], true) ?: [];
                $item['title'] = $title ? implode("", $title['values']) : '';
                $item['alert'] = $alert ? implode("", $alert['values']) : '';
            }
        }
        $gridModel = new GridDataModel($list, $count, [
            'perPage' => $page_size
        ]);

        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function ($filter) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    // 在这里添加字段过滤器
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('push_id', 'PUSH_ID')->placeholder('PUSH_ID');
                        $filter->equal('push_name', 'push名称')->placeholder('push名称');
                    });
                    $filter->expand();//默认展开
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'id');
                $grid->column('push_name', 'push名称')->copyable();
                $grid->column('push_id', 'push_id')->copyable();
                $grid->column('title', '主标题');
                $grid->column('alert', '副标题');
                $grid->column('push_type', '推送类型')->using(
                    PushLogModel::PUSH_ARR
                    , '未知')->dot([
                    1 => 'warning',
                    2 => 'info',
                ]);
                $grid->column('start_time', '定时时间');
//                $grid->column('creat_time', '创建时间');
//                $grid->column('end_time', '结束时间');
                $grid->column('push_status', '状态')->using(
                    PushLogModel::STATUS_ARR
                )->label([
                    PushLogModel::STATUS_WAIT => 'warning',
                    PushLogModel::STATUS_OVER => 'success',
                    PushLogModel::STATUS_FAIL => 'error',
                    PushLogModel::STATUS_SENDING => 'info',
                    PushLogModel::STATUS_DELETE => 'danger',
                ]);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableView();
                    $actions->disableEdit();
                    $html = ' <a class="fa del-data" data-state="' . PushLogModel::STATUS_DELETE . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">
                                    <span class="glyphicon" aria-hidden="true">删除</span></a>';
                    switch ($actions->row->push_status) {
                        case PushLogModel::STATUS_WAIT:
                            $actions->prepend($html);
                            break;
                    }
                });
            }
        );
        return $content
            ->header('push')
            ->description(' ')
            ->breadcrumb(['text' => 'push列表', 'url' => '/pushExcel/index'])
            ->body($grid->render());
    }

    /**
     * 新增
     * @param Request $request
     * @param Content $content
     * @param Form $form
     * @return Content
     */
    public function create(Request $request, Content $content, Form $form): Content
    {
        $form->disableReset();
        $this->_getForm($form);
        $form->hidden('push_type')->default(PushLogModel::PUSH_TYPE_GENERAL);
        $form->confirm('确定新增吗？');
        $form->action('/admin/pushExcel/save');

        $tab = new Tab();
        $tab->addLink('使用简介', url('/admin/pushExcel/index/introduce'), false);
        $tab->add('固定文案创建', $form->render(), true);
        $tab->addLink('自定义文案推送创建', url('/admin/pushExcel/cusCreate'), false);
        $content->row($tab);
        return $content
            ->header('固定文案创建')
            ->description(' ')
            ->breadcrumb(
                ['text' => 'push列表', 'url' => '/pushExcel/index'],
                ['text' => '新增']
            );

    }

    public function cusCreate(Request $request, Content $content, Form $form)
    {
        $form->disableReset();
        $form->confirm('确定新增吗？');
        $form->action('/admin/pushExcel/save');
//        $form->text('push_id', 'PUSH_ID')->required()->help('请联系相关推送业务负责人获取push_id');
        $form->text('name', 'push名称')->required();
        $form->datetime('start_time', '定时时间')->help('时间请大于当前5-10分钟，以免配置错误。');
        $form->hidden('push_type')->default(PushLogModel::PUSH_TYPE_SPECIAL);

        $form->list('title', '标题')->help('如果想将对应Excel列加入title，可将该列单独作为一行编写。例如:A(大写字母哦)');
        $form->list('alert', '副标题')->help('ssss');
        $form->linkSelect('link', '跳转链接');

        $form->file('excel', '上传Excel')->required()->removable()->help('请认真核对excel格式，第一列为uid.');

        $tab = new Tab();
        $tab->addLink('使用简介', url('/admin/pushExcel/index/introduce'), false);
        $tab->addLink('固定文案创建', url('/admin/pushExcel/index/create'), false);
        $tab->add('自定义文案推送创建', $form->render(), true);
        $content->row($tab);
        return $content
            ->header('自定义文案推送创建')
            ->description(' ')
            ->breadcrumb(
                ['text' => 'push列表', 'url' => '/pushExcel/index'],
                ['text' => '新增']
            );

    }

    /**
     * 简介
     * @param Content $content
     * @param Form $form
     * @return Content
     */
    public function introduce(Content $content, Form $form)
    {
        $form->disableReset();
        $form->disableSubmit();
        $form->display('*特别注意：')->default("<span style='color: red'>*推送前可以用一到两条本人或者同事的uid测试一下，看看文案等是否正确！避免大面积错误推送</span>");
        $form->display('使用建议：')->default("不要将推送时间，设置超过当前时间太长时间");
        $form->display('使用注意：')->default("Excel中不要有空的数据，否则会跳过！");
        $form->display('配置示例')->default('<img src = "https://img.haohaozhu.cn/Biz-imageShow/o_phbig/a46/7494131ss1440ru00qzmaz4?w=1080&h=668.74785591767&iv=1" style="width: 700px;height: 400px">');
        $form->display('excel格式示例')->default('<img src = "https://img.haohaozhu.cn/Biz-imageShow/o_phbig/c1c/da917313a0pg08700qzmf9u?w=1080&h=699.63224893918&iv=1" style="width: 700px;height: 400px">');
        $form->display('使用咨询：')->default('丛玉坤');

        $tab = new Tab();
        $tab->add('使用简介', $form->render(), true);
        $tab->addLink('固定文案创建', url('/admin/pushExcel/index/create'), false);
        $tab->addLink('自定义文案推送创建', url('/admin/pushExcel/cusCreate'), false);
        $content->row($tab);
        return $content
            ->header('自定义文案推送创建')
            ->description(' ')
            ->breadcrumb(
                ['text' => 'push列表', 'url' => '/pushExcel/index'],
                ['text' => '使用简介']
            );

    }


    /**
     * 审核
     * @param Request $request
     * @return JsonResponse
     */
    public function delete(Request $request): JsonResponse
    {
        try {
            $params = $request->all();

            $rule = [
                'id' => 'required|int',
                'status' => 'required|int',
            ];
            $validator_msg = Common::validatorRule($rule, $params);
            if ($validator_msg !== true) {
                throw  new \Exception($validator_msg);
            }
            $where['id'] = $params['id'];

            $admin_id = Admin::user()->id;
            $data['create_admin_id'] = $admin_id;
            $data['push_status'] = $params['status'];
            $info = PushLogModel::first(['id' => $params['id']]);
            if (!$info) {
                throw new \Exception('不存在的数据');
            }

            if ($info['start_time'] <= date("Y-m-d H:i:s")) {
                throw new \Exception("已开始,不能删除");
            }

            PushLogModel::update($data, $where);
            $success = [
                'title' => '操作成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }

        return response()->json($success);

    }


    /**
     * form
     * @param $baseForm
     */
    private function _getForm($baseForm): void
    {
//        $baseForm->text('push_id', 'PUSH_ID')->required()->help('请联系相关推送业务负责人获取push_id');
        $baseForm->text('name', 'push名称')->required();
        $baseForm->datetime('start_time', '定时时间')->help('时间请大于当前5-10分钟，以免误传发送');
        $baseForm->text('title', '标题')->required();
        $baseForm->text('alert', '副标题')->required();
        $baseForm->linkSelect('link', '跳转链接');
//        $baseForm->text('url', '链接');
        $baseForm->file('excel', '上传Excel')->required()->removable()->help('请认真核对excel格式，第一列为uid.');
    }

    /**
     * 保存
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function save(Request $request)
    {
        $params = $request->all();
        try {
            $rules = [
                'name' => "required",
                'title' => "required",
                'alert' => "required",
                'excel' => 'required',
                'link_type' => 'required',
                'start_time' => 'required|date',
            ];
            //验证参数
            $returnMsg = Common::validatorRule($rules, $params);
            if ($returnMsg !== true) {
                throw new \Exception($returnMsg);
            }
            $target_time = date("Y-m-d H:i:s", strtotime("+ 5minute"));
            if ($target_time > $params['start_time']) {
                throw new \Exception('定时时间，至少开始时间大于当前5分钟哦！');
            }

            $type = $params['push_type'];

            $file = $params['excel'];
            $fileName = '/tmp/pushExcel-' . $params['push_id'] . '-' . date('YmdHis') . '.xls';
            $res = move_uploaded_file($file, $fileName);
            if (!$res) {
                throw new \Exception('保存文件失败');
            }
            $data['push_id'] = \Doraemon\pockets\constInterface\Push\PushId::PUSH_EXCEL . time();
            $data['push_name'] = $params['name'];
            if ((int)$type === PushLogModel::PUSH_TYPE_GENERAL) {
                $data['alert'] = $params['alert'];
                $data['title'] = $params['title'];
            } else {
                $data['alert'] = json_encode($params['alert'], JSON_THROW_ON_ERROR);
                $data['title'] = json_encode($params['title'], JSON_THROW_ON_ERROR);
            }

            $linkParams = $params['link_params'] ? json_encode($params['link_params']) : '';
            $linkArr = LinkFormat::generateLink($params['link_type'], $linkParams);
            $url =  $linkArr && isset($linkArr[LinkConf::TEMPLATE_TYPE_APP]) ? $linkArr[LinkConf::TEMPLATE_TYPE_APP] : '';

            $data['url'] = $url;
            $data['push_type'] = $type;
            $data['file_name'] = $fileName;
            $data['create_admin_id'] = Admin::user()->id;
            $data['start_time'] = date("Y-m-d H:i:00", strtotime($params['start_time']));
            $where['push_id'] = $params['push_id'];
            $isset = PushLogModel::value($where);

            if (!is_null($isset)) {
                PushLogModel::update($data, $where);
            } else {
                PushLogModel::insert($data);
                $id = PushLogModel::id();
                if (!$id) {
                    throw new \Exception('sql保存信息失败');
                }
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '请重试,' . $e->getMessage()
            ]);
            return back()->with(compact('error'))->withInput();
        }
        $success = new MessageBag([
            'title' => '上传成功'
        ]);
        return redirect('/admin/pushExcel/index')->with(compact('success'));
    }


    private function operateScript()
    {
        return <<<SCRIPT
        $('.del-data').unbind('click').click(function(){
            var id= $(this).data('id');
            var status=$(this).data('state');
            let url = '/admin/pushExcel/index/delete'
            let params = {id:id,status:status}
            layer.confirm('确定要删除推送吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.title);
                    }
                });
            });
        });
SCRIPT;
    }

}